package com.js.myapp.common.activity;

// Created by JS on 2020/10/28.

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.js.basicpage.activity.BaseLoadingDialogActivity;
import com.js.basicutils.LogUtils;
import com.js.basicutils.NavigationBarUtil;
import com.js.basicutils.StatusBarUtil;
import com.js.basicutils.ToastUtils;
import com.js.myapp.R;
import com.qs.helper.printer.Device;
import com.qs.helper.printer.PrintService;
import com.qs.helper.printer.PrinterClass;
import com.qs.helper.printer.bt.BtService;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PrinterConnectActivity extends BaseLoadingDialogActivity {

    private static final String TAG = "PrinterConnectActivity";

    @BindView(R.id.back_text)
    TextView backText;
    @BindView(R.id.header_back)
    LinearLayout headerBack;
    @BindView(R.id.centre_title)
    TextView centreTitle;
    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.header)
    RelativeLayout header;
    @BindView(R.id.rb_type_one)
    RadioButton rbTypeOne;
    @BindView(R.id.rg_device_type)
    RadioGroup rgDeviceType;
    @BindView(R.id.btn_scan_device)
    Button btnScanDevice;
    @BindView(R.id.ll_device_list)
    LinearLayout llDeviceList;

    private PrinterConnectActivity mContext;
    Handler mhandler = null;
    Handler handler = null;
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;

    private boolean isBlueToothConnected = false; // 蓝牙是否连接成功
    private String blueToothMac = ""; // 连接的蓝牙地址

    public static List<Device> deviceList = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, PrinterConnectActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_printer_connect);
        StatusBarUtil.setStatusBarColor(mContext, R.color.color_actionbar_bg);
        NavigationBarUtil.setSysNavigationColor(mContext, Color.parseColor("#141d26"));
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        centreTitle.setText("打印机连接");
        rightTitle.setVisibility(View.GONE);
    }

    private void initData() {
        mhandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MESSAGE_READ:
                        byte[] readBuf = (byte[]) msg.obj;
                        String readMessage = new String(readBuf, 0, msg.arg1);
                        LogUtils.d(TAG, "readMessage=" + readMessage);
                        LogUtils.d(TAG, "readBuf:" + readBuf[0]);
                        if (readBuf[0] == 0x13) {
                            PrintService.isFUll = true;
                            showMsg(getResources().getString(R.string.str_printer_state) + ":" + getResources().getString(R.string.str_printer_bufferfull));
                        } else if (readBuf[0] == 0x11) {
                            PrintService.isFUll = false;
                            showMsg(getResources().getString(R.string.str_printer_state) + ":" + getResources().getString(R.string.str_printer_buffernull));
                        } else if (readBuf[0] == 0x08) {
                            showMsg(getResources().getString(R.string.str_printer_state) + ":" + getResources().getString(R.string.str_printer_nopaper));
                        } else if (readBuf[0] == 0x01) {
                            //ShowMsg(getResources().getString(R.string.str_printer_state)+":"+getResources().getString(R.string.str_printer_printing));
                        } else if (readBuf[0] == 0x04) {
                            showMsg(getResources().getString(R.string.str_printer_state) + ":" + getResources().getString(R.string.str_printer_hightemperature));
                        } else if (readBuf[0] == 0x02) {
                            showMsg(getResources().getString(R.string.str_printer_state) + ":" + getResources().getString(R.string.str_printer_lowpower));
                        } else {
                            if (readMessage.contains("800")) { // 80mm paper
                                PrintService.imageWidth = 72;
                                showMsg("纸张宽度：80mm");
                            } else if (readMessage.contains("580")) { // 58mm paper
                                PrintService.imageWidth = 48;
                                showMsg("纸张宽度：58mm");
                            }
                        }
                        break;
                    case MESSAGE_STATE_CHANGE:
                        LogUtils.d(TAG, "msg:" + msg.toString());
                        switch (msg.arg1) {
                            case PrinterClass.STATE_CONNECTED:
                                break;
                            case PrinterClass.STATE_CONNECTING:
                                showMsg("正在连接...");
                                break;
                            case PrinterClass.STATE_LISTEN:
                            case PrinterClass.STATE_NONE:
                                break;
                            case PrinterClass.SUCCESS_CONNECT:
                                PrintService.pl.write(new byte[]{0x1b, 0x2b});
                                try {
                                    Thread.sleep(10);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                for (int i = 0; i < llDeviceList.getChildCount(); i++) {
                                    View child = llDeviceList.getChildAt(i);
                                    TextView tvStatus = child.findViewById(R.id.tv_device_status);
                                    TextView tvMac = child.findViewById(R.id.tv_device_mac);
                                    String mac = "";
                                    if (tvMac != null) {
                                        mac = tvMac.getText().toString().trim();
                                    }
                                    if (tvStatus != null) {
                                        if (!TextUtils.isEmpty(blueToothMac) && TextUtils.equals(blueToothMac, mac)) {
                                            tvStatus.setText("已连接");
                                            tvStatus.setTextColor(getResources().getColor(R.color.red));
                                        } else {
                                            tvStatus.setText("未连接");
                                            tvStatus.setTextColor(getResources().getColor(R.color.text_colorA));
                                        }
                                    }

                                }
                                isBlueToothConnected = true;
                                showMsg("连接成功！");
                                break;
                            case PrinterClass.FAILED_CONNECT:
                                isBlueToothConnected = false;
                                blueToothMac = "";
                                for (int i = 0; i < llDeviceList.getChildCount(); i++) {
                                    View child = llDeviceList.getChildAt(i);
                                    TextView tvStatus = child.findViewById(R.id.tv_device_status);
                                    tvStatus.setText("未连接");
                                    tvStatus.setTextColor(getResources().getColor(R.color.red));
                                }
                                showMsg("连接失败！");
                                break;
                            case PrinterClass.LOSE_CONNECT:
                                isBlueToothConnected = false;
                                blueToothMac = "";
                                for (int i = 0; i < llDeviceList.getChildCount(); i++) {
                                    View child = llDeviceList.getChildAt(i);
                                    TextView tvStatus = child.findViewById(R.id.tv_device_status);
                                    tvStatus.setText("未连接");
                                    tvStatus.setTextColor(getResources().getColor(R.color.text_colorA));
                                }
//                                showMsg("失去连接...");
                        }
                        break;
                    case MESSAGE_WRITE:

                        break;
                }
                super.handleMessage(msg);
            }
        };

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        break;
                    case 1:
                        Device d = (Device) msg.obj;
                        if (d != null) {
                            if (deviceList == null) {
                                deviceList = new ArrayList<Device>();
                            }
                            if (!checkData(deviceList, d)) {
                                deviceList.add(d);
                            }
                        }
                        break;
                    case 2:
                        break;
                }
            }
        };
        PrintService.pl = new BtService(this, mhandler, handler);
    }

    private boolean checkData(List<Device> list, Device d) {
        for (Device device : list) {
            if (device.deviceAddress.equals(d.deviceAddress)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.header_back, R.id.btn_scan_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.header_back:
                moveTaskToBack(true);
                break;
            case R.id.btn_scan_device:
                scanDevice();
                break;
        }
    }

    /**
     * 扫描蓝牙设备
     */
    private void scanDevice() {
        if (PrintService.pl == null) {
            return;
        }
        Log.d(TAG, "scanDevice: 1");
        if (deviceList != null) {
            deviceList.clear();
            llDeviceList.removeAllViews();
            Log.d(TAG, "scanDevice: 2");
        }
        if (!PrintService.pl.IsOpen()) {
            Log.d(TAG, "scanDevice: 3");
            PrintService.pl.open(mContext);
        }
        Log.d(TAG, "scanDevice: 4");
        PrintService.pl.scan();
        Log.d(TAG, "scanDevice: 5");
        deviceList = PrintService.pl.getDeviceList();
        if (deviceList != null) {
            for (int i = 0; i < deviceList.size(); i++) {
                Device device = deviceList.get(i);
                LogUtils.d(TAG, "设备名：" + device.deviceName);
                LogUtils.d(TAG, "设备号：" + device.deviceAddress);
                if (device.deviceName.contains("printer")) {
                    addItem(device);
                }
            }
        }
    }

    /**
     * 添加蓝牙连接的设备
     *
     * @param device 设备
     */
    private void addItem(Device device) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_device, null);
        LinearLayout llDevice = view.findViewById(R.id.ll_device);
        TextView tvDeviceName = view.findViewById(R.id.tv_device_name);
        TextView tvDeviceMac = view.findViewById(R.id.tv_device_mac);
        TextView tvDeviceStatus = view.findViewById(R.id.tv_device_status);
        tvDeviceName.setText(device.deviceName);
        tvDeviceMac.setText(device.deviceAddress);
        tvDeviceStatus.setText("未连接");

        llDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBlueToothConnected) {
                    disconnectBlueToothDevice();
                } else {
                    PrintService.pl.connect(device.deviceAddress);
                    blueToothMac = device.deviceAddress;
                }
            }
        });
        llDeviceList.addView(view);
    }

    /**
     * 断开打印机连接
     */
    private void disconnectBlueToothDevice() {
        AlertDialog dialog = new AlertDialog.Builder(this).create();
        View view = View.inflate(this, R.layout.dialog_disconnect_device, null);
        Button btnConfirm = view.findViewById(R.id.btn_confirm);
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PrintService.pl.disconnect();
                blueToothMac = "";
                dialog.dismiss();
                isBlueToothConnected = false;
            }
        });
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        dialog.setCanceledOnTouchOutside(false);
        dialog.setView(view);
        dialog.show();

        //下面这段代码应放在dialog.show()的后面，不然在6.0或者更低版本中报错：
        //requestFeature() must be called before adding content
        Window window = dialog.getWindow();
        // 设置父布局为透明，以显现出自定义布局的圆角
        if (window != null) {
            View decorView = window.getDecorView();
            decorView.setBackgroundColor(Color.TRANSPARENT);
        }
    }

    private void showMsg(String msg) {
        ToastUtils.showToast(this, msg);
    }
}
